from selenium import webdriver
import time
import json
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

data_path='./data/'
    #暂时停用
class login_cookie():
    def __init__(self):
        pass
    def official(self):
        wb=webdriver.Chrome(data_path+'chromedriver.exe')
        wb.get('http://authserver.xju.edu.cn/authserver/login?service=http://zwyy.lib.xju.edu.cn/loginall.aspx?page=center')
        a=input()
        if wb.current_url=='http://zwyy.lib.xju.edu.cn/clientweb/xcus/ic2/Default.aspx?page=center':
            time.sleep(5)
            cookie=wb.get_cookies()
            wb.get('http://authserver.xju.edu.cn/')
            cookie2=wb.get_cookies()
            for c in cookie2:
                cookie.append(c)
            cookies=json.dumps(cookie)
            with open('../others/file/library_cookie', 'w') as f:
                f.write(cookies)
            print('cookie获取完成')
            wb.quit()
    def quick(self):
        pass

class appointment():
    def __init__(self,use,timer,where):
        self.TAG=True
        self.usename=use[0]
        self.password=use[1]
        self.start=timer[0]
        self.end=timer[1]
        self.where=where
        self.table=self.choose_table(self.where[1])
        self.floor={}
        self.set_dict={}
        self.floor['一楼']='//*[@id="item_list"]/ul/li[1]/a'
        self.floor['三楼']='//*[@id="item_list"]/ul/li[2]/a'
        self.set_dict['1FZ1-06']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[1]/ul/li[1]/a'
        self.set_dict['1FZ1_02']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[1]/ul/li[2]/a'
        self.set_dict['1FZ1']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[1]/ul/li[3]/a'
        self.set_dict['3FZ2']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[2]/ul/li[1]/a'
        self.set_dict['3F-A']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[2]/ul/li[2]/a'
        self.set_dict['3F-B']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[2]/ul/li[3]/a'
        self.set_dict['3F-C']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[2]/ul/li[4]/a'
        self.set_dict['3F-D']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[2]/ul/li[5]/a'
        self.set_dict['3F-E']='/html/body/div[5]/div/table/tbody/tr/td[1]/div/div/div/div[4]/ul/li[2]/ul/li[6]/a'
    def use_cookie(self):
        with open('../others/file/library_cookie', 'r')as f:
            cookielist=json.loads(f.read())
            print(cookielist)
        for c in cookielist:
            self.wb.add_cookie(c)
    def login(self):
        chrome_opts=webdriver.ChromeOptions()
        chrome_opts.add_argument("--headless")
        chrome_opts.add_argument("–disable-images")
        self.wb=webdriver.Chrome(executable_path=data_path+'chromedriver.exe',options=chrome_opts)
        self.wb.get('http://zwyy.lib.xju.edu.cn/ClientWeb/xcus/ic2/Default.aspx')
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="casLoginForm"]/p[5]/button')))
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="username"]')))
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="password"]')))
        self.wb.find_element_by_xpath('//*[@id="username"]').send_keys(self.usename)
        self.wb.find_element_by_xpath('//*[@id="password"]').send_keys(self.password)
        self.wb.find_element_by_xpath('//*[@id="casLoginForm"]/p[5]/button').click()
        self.wb.get_screenshot_as_file('a.png')
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, self.floor[self.where[0]])))
        self.wb.find_element_by_xpath(self.floor[self.where[0]]).click()
        print('用户登陆成功，等待查询时间开始')
    def refresh(self):
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, self.set_dict[self.where[1]])))
        self.wb.find_element_by_xpath(self.set_dict[self.where[1]]).click()
    def submit(self):
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, self.table)))
        self.wb.find_elements_by_xpath(self.table)[0].click()
        time.sleep(0.5)
        self.wb.switch_to.default_content()
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[8]/div[2]/form/div[1]/table/tbody[2]/tr[2]/td[2]/div/span[1]/select[1]')))
        start=self.wb.find_elements_by_xpath('/html/body/div[8]/div[2]/form/div[1]/table/tbody[2]/tr[2]/td[2]/div/span[1]/select[1]')[0]
        Select(start).select_by_visible_text(self.start)
        end=self.wb.find_elements_by_xpath('/html/body/div[8]/div[2]/form/div[1]/table/tbody[2]/tr[2]/td[2]/div/span[3]/select')[0]
        Select(end).select_by_visible_text(self.end)
        WebDriverWait(self.wb, 10).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[8]/div[2]/form/div[2]/input[1]')))
        self.wb.find_elements_by_xpath('/html/body/div[8]/div[2]/form/div[2]/input[1]')[0].click()
        time.sleep(20)
        self.wb.quit()
    def main(self):
        i=0
        self.login()
        while self.TAG:
            if time.strftime('%H:%M')=='11:46':
                for j in range(1,6):
                    try:
                        self.refresh()
                        self.submit()
                        print('第{0}次预约成功'.format(j))
                        break
                    except:
                        print('第{0}次预约失败'.format(j))
                        time.sleep(10)
                break
            else:
                time.sleep(10)
                i+=1
                print('正在第{0}次查询~~~~'.format(i))
        print('已经退出')
        self.wb.quit()
    def check_time(self):
        if time.strftime('%H:%M')=='12:38':
                for j in range(1,6):
                    try:
                        self.refresh()
                        self.submit()
                        print('第{0}次预约成功'.format(j))
                        self.wb.quit()
                        return 1
                    except:
                        print('第{0}次预约失败'.format(j))
                        time.sleep(5)
                        self.wb.quit()
                    return -1
        else:
            time.sleep(10)
            return 0
    def choose_table(self,floor):
        if floor=='3FZ2':
            return self.tabel_3FZ2()
        elif floor=='3F-A':
            return self.tabel_3F_A()
        else:
            return None
    def tabel_3FZ2(self):
        if self.where[1]==self.where[2].split('-')[0]:
            seat=int(self.where[2].split('-')[1])
            if seat>0 and seat<301:
                return '/html/body/div[5]/div/table/tbody/tr/td[2]/div/div[2]/div/div[2]/div[1]/div[1]/div[4]/div/div[2]/div[3]/div[{0}]'.format(seat)
            else:
                return None
        else:
            return None
    def tabel_3F_A(self):
        if len(self.where[2])==7 and self.where[2][:4]=='3F-A':
            num=int(self.where[2][-3:])
            if num>29 and num<112:
                num-=30
                return '/html/body/div[5]/div/table/tbody/tr/td[2]/div/div[2]/div/div[2]/div[1]/div[1]/div[4]/div/div[2]/div[3]/div[{0}]'.format(num)
            elif num==28:
                return '/html/body/div[5]/div/table/tbody/tr/td[2]/div/div[2]/div/div[2]/div[1]/div[1]/div[4]/div/div[2]/div[3]/div[83]'
            elif num==29:
                return '/html/body/div[5]/div/table/tbody/tr/td[2]/div/div[2]/div/div[2]/div[1]/div[1]/div[4]/div/div[2]/div[3]/div[84]'
            else:
                return None
        else:
            return None

# if __name__=='__main__':
#     where=('三楼','3F-A','3F-A111')
#     b=appointment(('20190810205','041236'),('19:55','23:00'),where=where)
#     b.main()
'''''''''
/html/body/div[5]/div/table/tbody/tr/td[2]/div/div[2]/div/div[2]/div[1]/div[1]/div[4]/div/div[2]/div[3]/div[170] 3fz2-170

/html/body/div[5]/div/table/tbody/tr/td[2]/div/div[2]/div/div[2]/div[1]/div[1]/div[4]/div/div[2]/div[3]/div[53]  3f-a083
/html/body/div[5]/div/table/tbody/tr/td[2]/div/div[2]/div/div[2]/div[1]/div[1]/div[4]/div/div[2]/div[3]/div[84]  3f-a029
'''''''''
